package org.linlinjava.litemall.wx.web;

import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallUserMember;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxUserMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author piao
 */
@RestController
@RequestMapping("/wx/userMember")
public class WxUserMemberController {
    @Autowired
    private WxUserMemberService wxUserMemberService;

    /**
     * 展示登录用户获得的会员
     *
     * @param userId
     * @return
     */
    @GetMapping("/getMember")
    public Object findByUserId(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.ok(wxUserMemberService.findByUserId(userId));
    }

    @GetMapping("/leftDays")
    public Object calculateLeftDays(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        LitemallUserMember userMember = wxUserMemberService.findByUserId(userId);
        if (userMember == null) {
            return 0;
        }
        LocalDateTime expirationTime = userMember.getExpirationTime();
        LocalDateTime now = LocalDateTime.now();
        Duration between = Duration.between(now, expirationTime);
        Duration duration = between.compareTo(Duration.ofDays(0)) > 0 ? between : Duration.ofDays(0);
        return ResponseUtil.ok(duration.toDays());
    }

}
